import { clone, min, omit, pick } from 'radash'
import { RouterLink } from 'vue-router'
import Layout from '@/layout/index.vue'
import { arrayToTree, renderIcon } from '@/utils'

const metaFields = ['title', 'icon', 'requiresAuth', 'roles', 'keepAlive', 'hide', 'order', 'href', 'activeMenu', 'withoutTab', 'pinTab', 'menuType']

function standardizedRoutes(route) {
  return clone(route).map((i) => {
    const route = omit(i, metaFields)
    Reflect.set(route, 'meta', pick(i, metaFields))
    return route
  })
}

export function createRoutes(routes) {
  // 构建meta字段
  let resultRouter = standardizedRoutes(routes)
  // 路由权限过滤
  // resultRouter = resultRouter.filter((i) => hasPermission(i.meta.roles))
  // 生成路由，不需要导入重定向文件
  const modules = import.meta.glob('@/views/**/*.vue')
  resultRouter = resultRouter.map((item) => {
    if (item.componentPath && !item.redirect) item.component = modules[`/src/views${item.componentPath}`]
    return item
  })
  // 生成路由树
  resultRouter = arrayToTree(resultRouter)
  const appRootRoute = {
    path: '/appRoot',
    name: 'appRoot',
    redirect: '/about',
    component: Layout,
    meta: {
      title: '',
      icon: 'icon-park-outline:home'
    },
    children: []
  }
  // 为路由设置正确的重定向路径
  setRedirect(resultRouter)
  // 将处理后的路由插入根路由
  appRootRoute.children = resultRouter
  return appRootRoute
}

// 生成一个需要保持活性的路由名称数组
export function generateCacheRoutes(routes) {
  return routes.filter((i) => i.keepAlive).map((i) => i.name)
}

function setRedirect(routes) {
  routes.forEach((route) => {
    if (route.children) {
      if (!route.redirect) {
        // 过滤掉没有隐藏的子元素集合
        const visibleChilds = route.children.filter((child) => !child.meta.hide)
        // 默认情况下，将page重定向到第一个子元素的路径
        let target = visibleChilds[0]
        // 用order属性过滤页面
        const orderChilds = visibleChilds.filter((child) => child.meta.order)
        if (orderChilds.length > 0) target = min(orderChilds, (i) => i.meta.order)
        if (target) route.redirect = target.path
      }
      setRedirect(route.children)
    }
  })
}

/**
 * @description 生成侧边菜单数据
 * @param {Routers} userRoutes
 * @returns 侧边菜单数据
 */
export function createMenus(userRoutes) {
  const resultMenus = standardizedRoutes(userRoutes)
  // 不需要显示的筛选菜单
  const visibleMenus = resultMenus.filter((route) => !route.meta.hide)
  // 生成边菜单
  return arrayToTree(transformAuthRoutesToMenus(visibleMenus))
}

/**
 * @description 将返回的路由表渲染为侧边栏
 * @param {Routers} userRoutes
 * @returns 侧边菜单数据
 */
function transformAuthRoutesToMenus(userRoutes) {
  // 未经允许过滤掉侧菜单
  return (
    userRoutes
      // .filter((i) => hasPermission(i.meta.roles))
      // 根据订单大小对菜单进行排序
      .sort((a, b) => {
        if (a.meta && a.meta.order && b.meta && b.meta.order) return a.meta.order - b.meta.order
        else if (a.meta && a.meta.order) return -1
        else if (b.meta && b.meta.order) return 1
        else return 0
      })
      // 转换为侧菜单数据结构
      .map((item) => {
        const target = {
          id: item.id,
          pid: item.pid,
          label: !item.meta.menuType || item.meta.menuType === 'page' ? () => <RouterLink to={item.path}>{item.meta.title}</RouterLink> : () => item.meta.title,
          key: item.path,
          icon: item.meta.icon ? renderIcon(item.meta.icon) : undefined
        }
        return target
      })
  )
}
